﻿
using DX_Recognize.Common;
using DX_Recognize.Entitys;
using DX_Recognize.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using ZwSoft.ZwCAD.ApplicationServices;
using ZwSoft.ZwCAD.Colors;
using ZwSoft.ZwCAD.DatabaseServices;
using ZwSoft.ZwCAD.EditorInput;
using ZwSoft.ZwCAD.Geometry;
using ZwSoft.ZwCAD.GraphicsInterface;
using Application = ZwSoft.ZwCAD.ApplicationServices.Application;
using Polyline = ZwSoft.ZwCAD.DatabaseServices.Polyline;

namespace DX_Recognize.AuxiliaryTool
{
    //CAD 公共辅助类
    public class CADAuxiliaryUtils
    {
        //当前开的文档
        public static Document Doc { get { return Application.DocumentManager.MdiActiveDocument; } }
        public static DocumentLock DocLock { get { return Doc.LockDocument(); } }

        //零件或孔闪烁显示
        public static void FlashHoleOrItem(List<ObjectId> ObjIdList)
        {
            bool isVis = false;
            Editor editor = null;
            if (ObjIdList.Count > 0)
            {
                try
                {
                    for (int i = 0; i < 10; ++i)
                    {
                        using (DocumentLock DocLock = Application.DocumentManager.MdiActiveDocument.LockDocument())
                        {
                            Document Doc = Application.DocumentManager.MdiActiveDocument;
                            var tr = Doc.TransactionManager.StartTransaction();
                            editor = Doc.Editor;
                            for (int j = 0; j < ObjIdList.Count; j++)
                            {
                                //报错
                                Entity Ent = tr.GetObject(ObjIdList[j], OpenMode.ForWrite) as Entity;
                                Ent.Visible = isVis;
                                isVis = !isVis;

                            }
                            tr.Commit();
                        }
                        //更新屏幕
                        editor.UpdateScreen();
                        Thread.Sleep(500);
                    }
                }
                catch (System.Exception)
                {

                    throw;
                }
                finally
                {
                    if(DocLock != null)
                        DocLock.Dispose();
                }
            }
        }

        //判断图层是否存在
        public static Boolean JudegLayerExist(string layerName)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                LayerTable layerTable = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                return layerTable.Has(layerName);
            }
        }

        //当前图档路径信息
        public static DwgFileInfo GetCurrentDrawingPath()
        {
            DwgFileInfo info = new DwgFileInfo();
            string path = (string)Application.GetSystemVariable("DWGPREFIX");
            string name = (string)Application.GetSystemVariable("DWGNAME");
            List<string> perfixList = path.Split('\\').ToList();

            info.complePath = path + name;
            info.dwgName = name;
            if (perfixList.Count > 0)
            {
                perfixList = perfixList.FindAll(item => item.Equals("")).ToList();
                if (perfixList.Count > 0)
                    info.batchNum = perfixList[perfixList.Count - 1];
            }
            return info;
        }

        //Create Layer
        public static void CreateLayerByName(String layerName)
        {
            DocumentLock m_DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable;
                    if (!layerTable.Has(layerName))
                    {
                        LayerTableRecord layer = new LayerTableRecord();
                        layer.Name = layerName;
                        layerTable.Add(layer);
                        tr.AddNewlyCreatedDBObject(layer, true);
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                if(m_DocumentLock != null)
                m_DocumentLock.Dispose();
            }
        }

        //删除某个图层上的实体
        public static void DeleteEntityOnLayer(String layerName)
        {
            DocumentLock m_DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                    if (layerTable.Has(layerName))
                    {
                        LayerTableRecord layer = tr.GetObject(layerTable[layerName], OpenMode.ForWrite) as LayerTableRecord;
                        layer.Erase();
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                if (m_DocumentLock != null)
                    m_DocumentLock.Dispose();
            }
        }

        //将图框添加到某个图层中
        public static void AddPicFrameToLayer(Utils.ConvertUtils.AMTypeUPloadRecordInfo Info, string layerName)
        {
            double? LX = null;
            double? RX = null;
            double? TY = null;
            double? BY = null;
            String areaInfoStr = Info.selectAreaCondiInfo;
            if(!String.IsNullOrEmpty(areaInfoStr))
            {
                JObject areaInfoJSON = JObject.Parse(areaInfoStr);
                string LXStr = areaInfoJSON["LX"].ToString();
                string RXStr = areaInfoJSON["RX"].ToString();
                string TYStr = areaInfoJSON["TY"].ToString();
                string BYStr = areaInfoJSON["BY"].ToString();
                if (LXStr != "")
                    LX = Double.Parse(LXStr);
                if (RXStr != "")
                    RX = Double.Parse(RXStr);
                if (TYStr != "")
                    TY = Double.Parse(TYStr);
                if (BYStr != "")
                    BY = Double.Parse(BYStr);

                Boolean CheckF = LX != null && RX != null && TY != null && BY != null;
                string dwgFilePath = Info.dwgfilePath;
                if (!File.Exists(dwgFilePath))
                {
                    MessageBox.Show(UserPromptErrorType.uploadFilePathError);
                    return;
                }

                try
                {
                    Document doc = Application.DocumentManager.Open(dwgFilePath, false);
                    if (CheckF)
                    {
                        DocumentLock m_DocumentLock = doc.LockDocument();
                        Database db = doc.Database;
                        try
                        {
                            using (Transaction trans = db.TransactionManager.StartTransaction())
                            {
                                DeleteEntityOnLayer(layerName);
                                CreateLayerByName(layerName);
                                Editor ed = doc.Editor;
                                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                                BlockTableRecord modelSpace = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                                LX -= 10;
                                RX += 10;
                                TY += 10;
                                BY -= 10;

                                // 创建一个多段线(//+图框)
                                Poly3dType type = Poly3dType.SimplePoly;
                                Point3d p1 = new Point3d((double)LX, (double)TY, 0);
                                Point3d p2 = new Point3d((double)RX, (double)TY, 0);
                                Point3d p3 = new Point3d((double)RX, (double)BY, 0);
                                Point3d p4 = new Point3d((double)LX, (double)BY, 0);
                                Point3d[] p3d = new Point3d[4] { p1, p2, p3, p4 };
                                Point3dCollection vertex = new Point3dCollection(p3d);
                                Polyline3d p = new Polyline3d(type, vertex, false);
                                p.Closed = true;
                                p.Layer = layerName;
                                //红色
                                p.Color = ZwSoft.ZwCAD.Colors.Color.FromRgb(255, 0, 0);
                                ObjectId pId = modelSpace.AppendEntity(p);
                                trans.AddNewlyCreatedDBObject(p, true);
                                // 创建填充对象
                                Hatch hatch = new Hatch();
                                modelSpace.AppendEntity(hatch);
                                trans.AddNewlyCreatedDBObject(hatch, true);
                                hatch.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                                hatch.Color = ZwSoft.ZwCAD.Colors.Color.FromRgb(255, 0, 0);
                                hatch.Layer = layerName;
                                hatch.Transparency = new Transparency(127);
                                // 添加多段线作为填充边界
                                ObjectIdCollection curves = new ObjectIdCollection();
                                curves.Add(p.ObjectId);
                                hatch.AppendLoop(HatchLoopTypes.Default, curves);
                                hatch.EvaluateHatch(true);
                                //提交事务
                                trans.Commit();
                            }
                        }
                        catch (System.Exception)
                        {
                            throw;
                        }
                        finally
                        {
                            if (m_DocumentLock != null)
                                m_DocumentLock.Dispose();
                        }
                    }
                }
                catch (Exception)
                {

                    throw;
                }
                
            }
        }

        //根据路径打开图纸
        public static void OpenDwgByFilePath(Utils.ConvertUtils.AMTypeUPloadRecordInfo Info)
        {
            string LayerName = "R2D_RecordPicFrame";
            string dwgFilePath = Info.dwgfilePath;
            DwgFileInfo nowFileInfo = GetCurrentDrawingPath();
            Boolean F = nowFileInfo.complePath.Equals(dwgFilePath);
            if (!F)
                AddPicFrameToLayer(Info, LayerName);
            return;
        }

        public static void ATypeDrawTVScrewHoleLabel(DWGVObjectIdInfo idInfo)
        {
            string layerName = "R2D_Label";
            CreateLayerByName(layerName);
            DrawTVScrewDimLabel(layerName, idInfo.AVObjectId);
            DrawTopSPGPEPHoleLabel(layerName, idInfo.TVObjectId);
        }

        public static void ATypeDrawAssemBoardThickLabel(ObjectId dimStyleId)
        {
            string boardThickLayerName = "R2D_BoardThick";
            CreateLayerByName(boardThickLayerName);
            DrawAssemblyBoardThickAndWidth(boardThickLayerName, dimStyleId);
        }

        public static void DrawTVScrewDimLabel(string layerName,ObjectId dimStyleId)
        {
            List<ScrewHole> smallScrewCList = HoleCandidateShareData.SmallScrewCList;
            List<ScrewHole> bigScrewCList = HoleCandidateShareData.BigScrewCList;
            List<ScrewHole> fallerScrewCList = HoleCandidateShareData.FallerScrewCList;
            DocumentLock m_DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    for (int i = 0; i < smallScrewCList.Count; i++)
                    {
                        double dimValue = smallScrewCList[i].Dim;
                        double CX = smallScrewCList[i].CenterPoint.CustomerPoint.X + dimValue * 0.2;
                        double CY = smallScrewCList[i].CenterPoint.CustomerPoint.Y + dimValue * 0.2;
                        DBText textEntity = new DBText();
                        textEntity.Position = new Point3d(CX, CY, 0);
                        textEntity.TextString = "M" + dimValue;
                        if(dimStyleId != ObjectId.Null)
                        {
                            textEntity.TextStyleId = dimStyleId;
                            textEntity.Height = dimValue * 0.4;
                        }
                        if (layerName != null)
                        {
                            LayerTable layerTable = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                            if (layerTable.Has(layerName))
                                textEntity.LayerId = layerTable[layerName];
                        }
                        btr.AppendEntity(textEntity);
                        tr.AddNewlyCreatedDBObject(textEntity, true);
                    }
                    for (int i = 0; i < bigScrewCList.Count; i++)
                    {
                        double dimValue = bigScrewCList[i].Dim;
                        double CX = bigScrewCList[i].CenterPoint.CustomerPoint.X + dimValue * 0.2;
                        double CY = bigScrewCList[i].CenterPoint.CustomerPoint.Y + dimValue * 0.2;
                        DBText textEntity = new DBText();
                        textEntity.Position = new Point3d(CX, CY, 0);
                        textEntity.TextString = "M" + dimValue;
                        if (dimStyleId != ObjectId.Null)
                        {
                            textEntity.TextStyleId = dimStyleId;
                            textEntity.Height = dimValue * 0.4;
                        }
                        if (layerName != null)
                        {
                            LayerTable layerTable = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                            if (layerTable.Has(layerName))
                                textEntity.LayerId = layerTable[layerName];
                        }
                        btr.AppendEntity(textEntity);
                        tr.AddNewlyCreatedDBObject(textEntity, true);
                    }
                    for (int i = 0; i < fallerScrewCList.Count; i++)
                    {
                        double dimValue = fallerScrewCList[i].Dim;
                        double CX = fallerScrewCList[i].CenterPoint.CustomerPoint.X + dimValue * 0.2;
                        double CY = fallerScrewCList[i].CenterPoint.CustomerPoint.Y + dimValue * 0.2;
                        DBText textEntity = new DBText();
                        textEntity.Position = new Point3d(CX, CY, 0);
                        textEntity.TextString = "M" + dimValue;
                        if (dimStyleId != ObjectId.Null)
                        {
                            textEntity.TextStyleId = dimStyleId;
                            textEntity.Height = dimValue * 0.4;
                        }
                        if (layerName != null)
                        {
                            LayerTable layerTable = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                            if (layerTable.Has(layerName))
                                textEntity.LayerId = layerTable[layerName];
                        }
                        btr.AppendEntity(textEntity);
                        tr.AddNewlyCreatedDBObject(textEntity, true);
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                //HttpUtils.CreateR2DCADLocalLog(ex.ToString(), DateTime.Now);
                throw;
            }
            finally
            {
                if (m_DocumentLock != null)
                    m_DocumentLock.Dispose();
            }
        }
 
        public static void DrawTopSPGPEPHoleLabel(string layerName,ObjectId dimStyleId)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            DocumentLock m_DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            List<ScrewHole> returnScrewCList = HoleCandidateShareData.ReturnPinCList;
            List<ScrewHole> gpScrewCList = HoleCandidateShareData.GPScrewCList;
            List<ScrewHole> spScrewCList = HoleCandidateShareData.SPScrewCList;
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable blockTable = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord modelSpace = tr.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    for (int i = 0; i < returnScrewCList.Count; i++)
                    {
                        Point3d point = new Point3d(returnScrewCList[i].CenterPoint.CustomerPoint.X, returnScrewCList[i].CenterPoint.CustomerPoint.Y, 0);
                        double radius = returnScrewCList[i].Dim / 2;
                        // 创建角度标注
                        DiametricDimension dim = new DiametricDimension();
                        double x45 = point.X + radius * Math.Cos(Math.PI / 4);
                        double y45 = point.Y + radius * Math.Sin(Math.PI / 4);
                        double x225 = point.X + radius * Math.Cos(5 * Math.PI / 4); 
                        double y225 = point.Y + radius * Math.Sin(5 * Math.PI / 4);
                        dim.ChordPoint = new Point3d(x45 , y45, point.Z);
                        dim.FarChordPoint = new Point3d(x225, y225, point.Z);
                        dim.LeaderLength = radius;
                        dim.DimensionText = "RP" + "Φ" + returnScrewCList[i].Dim.ToString();
                        if(dimStyleId != ObjectId.Null)
                        {
                            dim.TextStyleId = dimStyleId;
                            dim.Dimtxt = radius * 0.4;
                        }
                        if (!string.IsNullOrEmpty(layerName))
                        {
                            LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                            if (layerTable.Has(layerName))
                                dim.LayerId = layerTable[layerName];
                        }
                        modelSpace.AppendEntity(dim);
                        tr.AddNewlyCreatedDBObject(dim, true);
                    }
                    for(int i = 0; i < gpScrewCList.Count; i++)
                    {
                        Point3d point = new Point3d(gpScrewCList[i].CenterPoint.CustomerPoint.X, gpScrewCList[i].CenterPoint.CustomerPoint.Y, 0);
                        double radius = gpScrewCList[i].Dim / 2;
                        DiametricDimension dim = new DiametricDimension();
                        double x30 = point.X + radius * Math.Cos(Math.PI / 6);
                        double y30 = point.Y + radius * Math.Sin(Math.PI / 6);
                        double x150 = point.X + radius * Math.Cos(6 * Math.PI / 5);
                        double y150 = point.Y + radius * Math.Sin(6 * Math.PI / 5);
                        dim.ChordPoint = new Point3d(x30, y30, point.Z);
                        dim.FarChordPoint = new Point3d(x150, y150, point.Z);
                        dim.LeaderLength = radius;
                        dim.DimensionText = "GP" + "Φ" + gpScrewCList[i].Dim.ToString();
                        if (dimStyleId != ObjectId.Null)
                        {
                            dim.TextStyleId = dimStyleId;
                            dim.Dimtxt = radius * 0.4;
                        }
                        if (!string.IsNullOrEmpty(layerName))
                        {
                            LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                            if (layerTable.Has(layerName))
                                dim.LayerId = layerTable[layerName];
                        }
                        modelSpace.AppendEntity(dim);
                        tr.AddNewlyCreatedDBObject(dim, true);
                    }
                    if (CADCommonForm.MoldTypeStr.Equals("PP"))
                    {
                        for (int i = 0; i < spScrewCList.Count; i++)
                        {
                            Point3d point = new Point3d(spScrewCList[i].CenterPoint.CustomerPoint.X, spScrewCList[i].CenterPoint.CustomerPoint.Y, 0);
                            double radius = spScrewCList[i].Dim / 2;
                            DiametricDimension dim = new DiametricDimension();
                            double x45 = point.X + radius * Math.Cos(Math.PI / 4);
                            double y45 = point.Y + radius * Math.Sin(Math.PI / 4);
                            double x225 = point.X + radius * Math.Cos(5 * Math.PI / 4);
                            double y225 = point.Y + radius * Math.Sin(5 * Math.PI / 4);
                            dim.ChordPoint = new Point3d(x45, y45, point.Z);
                            dim.FarChordPoint = new Point3d(x225, y225, point.Z);
                            dim.LeaderLength = radius;
                            dim.DimensionText = "SP" + "Φ" + spScrewCList[i].Dim.ToString();
                            if (dimStyleId != ObjectId.Null)
                            {
                                dim.TextStyleId = dimStyleId;
                                dim.Dimtxt = radius * 0.4;
                            }
                            if (!string.IsNullOrEmpty(layerName))
                            {
                                LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                                if (layerTable.Has(layerName))
                                    dim.LayerId = layerTable[layerName];
                            }
                            modelSpace.AppendEntity(dim);
                            tr.AddNewlyCreatedDBObject(dim, true);
                        }
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                if (m_DocumentLock != null)
                    m_DocumentLock.Dispose();
            }
        }

        //Set Plate Thick
        public static void DrawAssemblyBoardThickAndWidth(string layerName,ObjectId dimStyleId)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            DocumentLock m_DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            List<BoardSectionItem> targetList = AssemblyShareData.ASectionList;
            if (targetList.Count > 0)
            {
                try
                {
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        BlockTable blockTable = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        BlockTableRecord modelSpace = tr.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                        int tpNextIndex = -1;
                        int tpIndex = targetList.FindIndex(item => item.BoardCode.Equals("tpBoard") 
                        || item.BoardCode.Equals("cpBoard"));
                        if (tpIndex != -1)
                            tpNextIndex = tpIndex + 1;
                        //倒数第二件
                        int beforeLastBoardIndex = targetList.Count - 2;
                        double dimtxt = 1;
                        if (targetList.Count > 0)
                            dimtxt = targetList.Select(item => item.PlateThick).ToList().Min() * 0.3;
                        for (int i = 0; i < targetList.Count; i++)
                        {
                           AlignedDimension ro = new AlignedDimension();
                           double ptValue = targetList[i].PlateThick;
                            if(dimStyleId != ObjectId.Null)
                            {
                                ro.TextStyleId = dimStyleId;
                                ro.Dimtxt = dimtxt;
                                ro.Dimdec = 1;
                            }
                            ro.TextRotation = Math.PI / 2;
                            if (tpNextIndex != -1 && i == tpNextIndex)
                           {
                                //起点用下沿线的X
                                double X1 = targetList[i].BottomLine.EndPoint.CustomerPoint.X;
                                double Y1 = targetList[i].OverheadLine.EndPoint.CustomerPoint.Y;
                                Point3d point1 = new Point3d(X1, Y1, 0);
                                double X2 = targetList[i].BottomLine.EndPoint.CustomerPoint.X;
                                double Y2 = targetList[i].BottomLine.EndPoint.CustomerPoint.Y;
                                Point3d point2 = new Point3d(X2, Y2, 0);
                                ro.XLine1Point = point1;
                                ro.XLine2Point = point2;
                                ro.DimLinePoint = new Point3d((point1.X + point2.X) / 2 + 50, (point1.Y + point2.Y) / 2, 0);
                            }
                            else
                            {
                                Boolean lasatbutOneF = beforeLastBoardIndex == i;
                                Boolean F = targetList[i].BoardCode.Equals("epBoard")
                                || targetList[i].BoardCode.Equals("epBoard")
                                || targetList[i].BoardCode.Equals("fangtie");
                                if (F || lasatbutOneF)
                                {
                                    //终点用上沿线的X
                                    double X1 = targetList[i].OverheadLine.EndPoint.CustomerPoint.X;
                                    double Y1 = targetList[i].OverheadLine.EndPoint.CustomerPoint.Y;
                                    Point3d point1 = new Point3d(X1, Y1, 0);
                                    double X2 = targetList[i].OverheadLine.EndPoint.CustomerPoint.X;
                                    double Y2 = targetList[i].BottomLine.EndPoint.CustomerPoint.Y;
                                    Point3d point2 = new Point3d(X2, Y2, 0);
                                    ro.XLine1Point = point1;
                                    ro.XLine2Point = point2;
                                    ro.DimLinePoint = new Point3d((point1.X + point2.X) / 2 + 50, (point1.Y + point2.Y) / 2, 0);
                                }
                                else
                                {
                                    double X1 = targetList[i].OverheadLine.EndPoint.CustomerPoint.X;
                                    double Y1 = targetList[i].OverheadLine.EndPoint.CustomerPoint.Y;
                                    double X2 = targetList[i].BottomLine.EndPoint.CustomerPoint.X;
                                    double Y2 = targetList[i].BottomLine.EndPoint.CustomerPoint.Y;
                                    if(X1 == X2)
                                    {
                                        Point3d point1 = new Point3d(X1, Y1, 0);
                                        Point3d point2 = new Point3d(X2, Y2, 0);
                                        ro.XLine1Point = point1;
                                        ro.XLine2Point = point2;
                                        ro.DimLinePoint = new Point3d((point1.X + point2.X) / 2 + 50, (point1.Y + point2.Y) / 2, 0);
                                    }
                                    else
                                    {
                                        double bigX = X1 > X2 ? X1 : X2;
                                        Point3d point1 = new Point3d(bigX, Y1, 0);
                                        Point3d point2 = new Point3d(bigX, Y2, 0);
                                        ro.XLine1Point = point1;
                                        ro.XLine2Point = point2;
                                        ro.DimLinePoint = new Point3d((point1.X + point2.X) / 2 + 50, (point1.Y + point2.Y) / 2, 0);
                                    }
                                }
                            }
                            //Set Layer
                            if (!string.IsNullOrEmpty(layerName))
                            {
                                LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                                if (layerTable.Has(layerName))
                                    ro.LayerId = layerTable[layerName];
                            }
                            modelSpace.AppendEntity(ro);
                            tr.AddNewlyCreatedDBObject(ro, true);
                        }
                        tr.Commit();
                        doc.Editor.Regen();
                    }
                }
                catch (System.Exception ex)
                {
                    //HttpUtils.CreateR2DCADLocalLog(ex.ToString(), DateTime.Now);
                    throw;
                }
                finally
                {
                    if (m_DocumentLock != null)
                        m_DocumentLock.Dispose();
                }
            }
            
        }

        public static string FindFitSysFontPath()
        {
            string Path1 = "C:\\Program Files\\ZWSOFT\\ZWCAD 2023\\DIM.SHX";
            string Path2 = "C:\\Program Files\\ZWSOFT\\ZWCAD 2024\\DIM.SHX";
            string Path3 = "C:\\Windows\\Fonts\\arial.ttf";
            string Path4 = "D:\\DX\\ZW\\2D\\DIM.SHX";
            Boolean F1 = File.Exists(Path1);
            if(F1)
                return Path1;
            Boolean F2 = File.Exists(Path2);
            if (F2)
                return Path2;
            Boolean F3 = File.Exists(Path3);
            if (F3)
                return Path3;
            Boolean F4 = File.Exists(Path4);
            if (F4)
                return Path4;
            return Path4;
        }

        public static void CreateDXTextStyle(String fontFilePath)
        {
            List<BoardSectionItem> operList = AssemblyShareData.ASectionList;
            if(operList.Count > 0)
            {
                List<double> thickList = operList.Select(item => item.PlateThick).ToList();
                double minT = thickList.Min();
                double TVSize = minT / 3;
                double AVSize = minT / 2;
                try
                {
                    Document doc = Application.DocumentManager.MdiActiveDocument;
                    Database db = doc.Database;
                    Editor editor = doc.Editor;
                    string TVTextStyleName = "DX_TVTextStyle";
                    string AVTextStyleName = "DX_AVTextStyle";
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        TextStyleTable textStyleTable = tr.GetObject(db.TextStyleTableId, OpenMode.ForWrite) as TextStyleTable;
                        if (!textStyleTable.Has(TVTextStyleName))
                        {
                            TextStyleTableRecord newTVTextStyle = new TextStyleTableRecord();
                            newTVTextStyle.Name = TVTextStyleName;
                            if (fontFilePath != null)
                                newTVTextStyle.FileName = fontFilePath;
                            newTVTextStyle.TextSize = TVSize;
                            textStyleTable.Add(newTVTextStyle);
                            tr.AddNewlyCreatedDBObject(newTVTextStyle, true);
                        }
                        if (!textStyleTable.Has(AVTextStyleName))
                        {
                            TextStyleTableRecord newAVTextStyle = new TextStyleTableRecord();
                            newAVTextStyle.Name = AVTextStyleName;
                            if (fontFilePath != null)
                                newAVTextStyle.FileName = fontFilePath;
                            newAVTextStyle.TextSize = AVSize;
                            textStyleTable.Add(newAVTextStyle);
                            tr.AddNewlyCreatedDBObject(newAVTextStyle, true);
                        }
                        tr.Commit();
                        editor.WriteMessage("创建标注成功");
                    }
                }
                catch (Exception ex)
                {
                    //HttpUtils.CreateR2DCADLocalLog(ex.ToString(), DateTime.Now);
                    throw;
                }
            }
        }

        public static DWGVObjectIdInfo GetDefineIdInfo()
        {
            DWGVObjectIdInfo Res = new DWGVObjectIdInfo();
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            string TVTextStyleName = "DX_TVTextStyle";
            string AVTextStyleName = "DX_AVTextStyle";
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    TextStyleTable dimStyleTable = tr.GetObject(db.TextStyleTableId, OpenMode.ForWrite) as TextStyleTable;
                    foreach (ObjectId id in dimStyleTable)
                    {
                        TextStyleTableRecord style = (TextStyleTableRecord)tr.GetObject(id, OpenMode.ForRead);

                        if (style.Name.Equals(TVTextStyleName, StringComparison.OrdinalIgnoreCase))
                            Res.TVObjectId = id;

                        if (style.Name.Equals(AVTextStyleName, StringComparison.OrdinalIgnoreCase))
                            Res.AVObjectId = id;

                        if (Res.TVObjectId != ObjectId.Null && Res.AVObjectId != ObjectId.Null)
                            break;
                    }
                    tr.Commit();
                }
            }
            catch (Exception ex)
            {
                //HttpUtils.CreateR2DCADLocalLog(ex.ToString(), DateTime.Now);
                throw;
            }
            return Res;
        }

        //已知两点 绘制直线标注
        public static void DrawTwoLineLabel(Point3d point1, Point3d point2, double XoffsetDist, double YoffsetDist)
        {
            Document doc = ZwSoft.ZwCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            DocumentLock m_DocumentLock = doc.LockDocument();
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable blockTable = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord modelSpace = tr.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    AlignedDimension ro = new AlignedDimension(point1, point2, new Point3d(point1.X + XoffsetDist, point1.Y + YoffsetDist, 0), "", ObjectId.Null);
                    modelSpace.AppendEntity(ro);
                    tr.AddNewlyCreatedDBObject(ro, true);
                    tr.Commit();
                    doc.Editor.Regen();
                }
            }
            catch (ZwSoft.ZwCAD.Runtime.Exception e)
            {
                throw;
            }
            finally
            {
                if (m_DocumentLock != null)
                    m_DocumentLock.Dispose();
            }
        }

        public static void ATypeDrawBoardAndItemLabel(ObjectId textStyleId, Point3d point1, Point3d point2, double XoffsetDist, double YoffsetDist,
            string DrawType = "B", string DrawDirType = "X",double txtSize = 0)
        {
            if(DrawType.Equals("B"))
            {
                double size = MoldBaseShare.Length * 0.02;
                ATypeDrawBoardItemLabelLogic(textStyleId, point1, point2, XoffsetDist, YoffsetDist, size,DrawDirType);
            }
            if (DrawType.Equals("I"))
            {
                double size = txtSize * 0.2;
                ATypeDrawBoardItemLabelLogic(textStyleId, point1, point2, XoffsetDist, YoffsetDist, size, DrawDirType);
            }
        }

        public static void ATypeDrawBoardItemLabelLogic(ObjectId textStyleId, Point3d point1, Point3d point2, double XoffsetDist, double YoffsetDist, double txtSize,string DrawDirType = "X")
        {
            Document doc = ZwSoft.ZwCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            DocumentLock m_DocumentLock = doc.LockDocument();
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable blockTable = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord modelSpace = tr.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    AlignedDimension ro = new AlignedDimension(point1, point2, new Point3d(point1.X + XoffsetDist, point1.Y + YoffsetDist, 0), "", ObjectId.Null);
                    if(textStyleId != ObjectId.Null)
                    {
                        ro.Dimtxt = txtSize;
                        ro.TextStyleId = textStyleId;
                        ro.Dimdec = 2;
                    }
                    if(DrawDirType.Equals("Y"))
                        ro.TextRotation = Math.PI / 2;
                    modelSpace.AppendEntity(ro);
                    tr.AddNewlyCreatedDBObject(ro, true);
                    tr.Commit();
                    doc.Editor.Regen();
                }
            }
            catch (ZwSoft.ZwCAD.Runtime.Exception ex)
            {
                //HttpUtils.CreateR2DCADLocalLog(ex.ToString(), DateTime.Now);
                throw;
            }
            finally
            {
                if (m_DocumentLock != null)
                    m_DocumentLock.Dispose();
            }
        }

    }

    public class DwgFileInfo
    {
        //批次号 放文件的目录
        public string batchNum { get; set; }
        //全路径
        public string complePath { get; set; }
        public string dwgName { get; set; }
    }

}

